
package com.trial.area.trade.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jfinal.weixin.sdk.api.PaymentApi;
import com.trial.area.config.ConfigUtils;
import com.trial.area.coupon.dao.CouponDao;
import com.trial.area.coupon.entity.CouponVO;
import com.trial.area.trade.dao.ChargeRecordDao;
import com.trial.area.trade.dao.TradeRecordDao;
import com.trial.area.trade.entity.ChargeRecordVO;
import com.trial.area.trade.entity.TradeRecordVO;
import com.trial.area.trade.param.ChargeRecordParam;
import com.trial.area.weixin.common.WeixinUtils;

/**
 * 支付记录Service实现类
 *
 * @author 朱国军
 * @version 2016年07月17日 朱国军
 */
@Service
public class ChargeRecordService {

    @Autowired
    private ChargeRecordDao chargeRecordDao;
    
    @Autowired
    private TradeRecordDao tradeRecordDao;
    
    @Autowired
    private CouponDao couponDao;

    /**
     * 新增，注：返回的添加的条数，获取主键用entity.getId();
     *
     * @param entity 要增加的支付记录对象
     * @return 返回新增的条数
     */
    public Integer insert(ChargeRecordVO entity) {
        return chargeRecordDao.insert(entity);
    }

    /**
     * 修改
     *
     * @param entity 要修改的支付记录对象
     * @return 返回修改的条数
     */
    public Integer update(ChargeRecordVO entity) {
        return chargeRecordDao.update(entity);
    }

    /**
     * 根据ID获取支付记录实体
     *
     * @param id 主键
     * @return 支付记录信息
     */
    public ChargeRecordVO findById(String id) {
        return chargeRecordDao.findById(id);
    }
    
    /**
     * 根据交易记录ID获取支付记录实体
     *
     * @param tradeId 交易记录ID
     * @return 支付记录信息
     */
    public ChargeRecordVO findByTradeId(String tradeId) {
        return chargeRecordDao.findByTradeId(tradeId);
    }

    /**
     * 按查询条件【分页】查询
     *
     * @param param 支付记录查询条件
     * @return 支付记录列表
     */
    public List<ChargeRecordVO> queryByPage(ChargeRecordParam param) {
        return chargeRecordDao.queryByPage(param);
    }

    /**
     * 根据ID删除支付记录
     *
     * @param id 主键
     */
    public Integer delete(String id) {
        return chargeRecordDao.delete(id);
    }

    /**
     * 从微信查询订单状态
     *
     * @param tradeNo
     * @return
     */
    public Map<String, String> queryOrderStatus(String tradeNo) {
        String appId = WeixinUtils.getApiConfig().getAppId();
        String mchId = ConfigUtils.getStringValueByKey("weixin_mch_id");
        String paternerKey = ConfigUtils.getStringValueByKey("weixin_paterner_key");
        Map<String, String> orderQueryResult = PaymentApi.queryByOutTradeNo(appId, mchId, paternerKey, tradeNo);

        Map<String, String> orderResult = new HashMap<String, String>();
        orderResult.put("result", orderQueryResult.get("trade_state"));
        orderResult.put("message", orderQueryResult.get("trade_state_desc"));
        return orderResult;
    }
    
    /**
     * 查询并更新订单状态
     *
     * @param tradeNo
     */
    public Map<String, String> updateOrderStatus(ChargeRecordVO chargeRecordVO, String pagePayResult) {
        
        TradeRecordVO tradeRecordVO = tradeRecordDao.findById(chargeRecordVO.getTradeId());
        
        Map<String, String> orderResult = queryOrderStatus(chargeRecordVO.getTradeNo());
        
        // NOTPAY 和 USERPAYING 中不用处理
        if (StringUtils.equals("SUCCESS", orderResult.get("result"))) {
            tradeRecordVO.setTradeState(2);
            tradeRecordDao.update(tradeRecordVO);

            chargeRecordVO.setChargeState(3);
            chargeRecordVO.setPagePayResult(pagePayResult);
            chargeRecordVO.setServicePayResult(orderResult.get("result"));
            chargeRecordDao.update(chargeRecordVO);
        } else if (StringUtils.equals("REFUND", orderResult.get("result"))) {
            tradeRecordVO.setTradeState(11);
            tradeRecordDao.update(tradeRecordVO);

            updateCouponStatus(tradeRecordVO.getCouponId());

            chargeRecordVO.setChargeState(13);
            chargeRecordVO.setPagePayResult(pagePayResult);
            chargeRecordVO.setServicePayResult(orderResult.get("result"));
            chargeRecordDao.update(chargeRecordVO);
        } else if (StringUtils.equals("CLOSED", orderResult.get("result")) || StringUtils.equals("REVOKED", orderResult.get("result"))
            || StringUtils.equals("PAYERROR", orderResult.get("result"))) {
            tradeRecordVO.setTradeState(11);
            tradeRecordDao.update(tradeRecordVO);
            
            updateCouponStatus(tradeRecordVO.getCouponId());

            chargeRecordVO.setChargeState(12);
            chargeRecordVO.setPagePayResult(pagePayResult);
            chargeRecordVO.setServicePayResult(orderResult.get("result"));
            chargeRecordDao.update(chargeRecordVO);
        }
        return orderResult;
    }
    
    /**
     * 将优惠券设置为：已兑换（未使用）
     *
     * @param couponId 优惠券ID
     */
    private void updateCouponStatus(String couponId) {
        CouponVO couponVO = new CouponVO();
        couponVO.setCouponId(couponId);
        couponVO.setCouponState(2);
        couponDao.update(couponVO);
    }
}
